package com.uduemc.biso.node.web.service.byfeign.impl;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.feign.HRepertoryFeign;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.service.byfeign.RepertoryService;

import cn.hutool.core.codec.Base64;

@Service
public class RepertoryServiceImpl implements RepertoryService {

	@Autowired
	private HRepertoryFeign hRepertoryFeign;

	@Autowired
	private RequestHolder requestHolder;

	@Override
	public HRepertory getRepertoryByHostIdAndId(long hostId, long id)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		RestResult restResult = hRepertoryFeign.findOne(id);
		HRepertory data = RestResultUtil.data(restResult, HRepertory.class);
		if (data == null || data.getHostId() == null || data.getHostId().longValue() != hostId) {
			return null;
		}
		return data;
	}

	@Override
	public HRepertory getAccessRepertoryById(long id)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		long hostId = requestHolder.getHostId();
		return getRepertoryByHostIdAndId(hostId, id);
	}

	@Override
	public HRepertory getInfoByHostIdFilePath(long hostId, String filePath)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		RestResult restResult = hRepertoryFeign.findInfoByHostIdFilePath(hostId, filePath);
		HRepertory data = RestResultUtil.data(restResult, HRepertory.class);
		if (data == null || data.getHostId() == null || data.getHostId().longValue() != hostId) {
			return null;
		}
		return data;
	}

	@Override
	public HRepertory findByOriginalFilenameAndToDay(long hostId, long createAt, String originalFilename)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		originalFilename = Base64.encode(originalFilename);
		RestResult restResult = hRepertoryFeign.findByOriginalFilenameAndToDay(hostId, createAt, originalFilename);
		HRepertory data = RestResultUtil.data(restResult, HRepertory.class);
		if (data == null || data.getHostId() == null || data.getHostId().longValue() != hostId) {
			return null;
		}
		return data;
	}

}
